package com.net.tkc.pro.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩包、压缩或解压
 */
public class ZIPUtil {
    /**
     * 打成压缩包
     * @param files 需要压缩的文件列表
     * @param ZIPFile 压缩后的ZIP文件
     * @return boolean
     */
    public boolean ToZIPFiles(File[] files,File ZIPFile){
        boolean flag =true;
        if(!ZIPFile.exists()){//如果压缩包不存在，生成一个空的文件
            try{
                ZIPFile.createNewFile();//生成文件
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        FileOutputStream fileOutputStream = null;//生成文件输出对象
        ZipOutputStream zipOutputStream = null;//生成压缩包输出对象
        FileInputStream fileInputStream = null;//文件输入流
        try{
            fileOutputStream = new FileOutputStream(ZIPFile);//实例化输入流
            zipOutputStream = new ZipOutputStream(fileOutputStream);//实例化ZIP输出
            ZipEntry zipEntry = null;//新建ZIP压缩包实例
            for(File f:files){//遍历数组 放入ZIP包中
                fileInputStream = new FileInputStream(f);//将单个文件读入
                zipEntry = new ZipEntry(f.getName());//实例化zip对象
                zipOutputStream.putNextEntry(zipEntry);//将zip包存储
                int len;
                byte[] buffer = new byte[1024];//读取字节，每次都是1024
                while ((len=fileInputStream.read(buffer))>0){//读取字节并写入
                    zipOutputStream.write(buffer,0,len);

                }
            }
            zipOutputStream.closeEntry();//关闭zip写入对象
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();

        }catch (Exception e){
            e.printStackTrace();
            flag=false;
        }
    return flag;
    }
}
